(function ($) {
	var mustPull,optionPull;
	var mustStart = 0, optionStart = 0,Limit = 20;
	var mustPulling = false,optionPulling = false;
	var mustData=[],optionData=[];
	var loginID = '',TomcatUrl = ''
	$.init();
	$.plusReady(function () {
	    baseSetup();
	})
	if (!mui.os.plus) {
		baseSetup()
	}
	//待培训
	function getMustData(){
		if (mustPulling) {
			mustPull.endPullUpToRefresh()
			return;
		}
		mustPulling = true
		// parr 开始日期^结束日期^查询条件类型(1:主题，2：类型，3：级别，4：状态)^Y必修 N选修^O:预约，S:"学员培训"，T:"讲师培训"
		var parr = '^^1^Y^O'; //Y必修 N选修 1是主题
		var pdict = {'parr':parr,'input':$('#search')[0].value,'loginID':loginID,'start':mustStart,'limit':Limit}
		//console.log(JSON.stringify(pdict))
		var paramDict = {'method':'web.INMTeaComm:FindDrillReleaseList','params':JSON.stringify(pdict),'type':'RecQuery'}
		$.DHCWebService(paramDict, function(result) {
			//console.log(JSON.stringify(result))
			mustPulling = false
			if (result['msgcode'] != '1') {
				mui.toast(result.msg)
				mustPull.endPullUpToRefresh();
				return
			}
			var dataArr = result.data
			if (mustStart == 0) {
				mustData = dataArr
				mui('#mustUL').off('tap','.baseBtn',baseBtnTapped)
				$('#mustUL')[0].innerHTML = ''
				mui('#mustUL').on('tap','.baseBtn',baseBtnTapped)
			}else{
				mustData = mustData.concat(dataArr)
			}
			updateMustUI(dataArr,'mustUL')
			if (dataArr.length < Limit) {
				mustPull.endPullUpToRefresh(true);
			}else{
				mustPull.endPullUpToRefresh();
			}
			mustStart += dataArr.length;
		}, function(errorStr) {
			mustPull.endPullUpToRefresh();
			mustPulling = false
		});
	}
	function updateMustUI(dataArr,ulId){
		var mustUL = $('#'+ulId)[0]
		var index = 0
		var text = '预约'
		if (ulId != 'mustUL') {
			index = 1
			text = '报名'
		}
		var currDateTime = getCurrDateTime()
		var oldcount = mustUL.querySelectorAll('li').length
		for(var i=0; i < dataArr.length; i++){
			var dict = dataArr[i]
			var levelDesc = ''//H:院级,L:科级,W:病区
			var level = dict['ReleaseLevel']
			if (level == 'H') {
				levelDesc = '院级'
			}else if (level == 'L') {
				levelDesc = '科级'
			}else if (level == 'W') {
				levelDesc = '病区'
			}
			var TimeList = (dict['TimeList']||'').split('「')
			//2024-01-01 00:00」2024-01-10 00:00」2023-12-20 00:00」考核地点1」2「
			//2024-01-11 00:00」2024-01-21 00:00」2024-01-01 00:00」考核地点2」3「
			//2024-01-21 00:00」2024-01-30 00:00」2024-01-15 00:00」考核地点3」4",
			var html = '<div class="classTitle">'+dict['ReleaseDesc']+'<div>'+TimeList.length+'批次</div></div>'+ //'+dict['']+'
				'<div class="classInfo"><div>'+levelDesc+'</div><div>'+(dict['ReleaseDrillTypeDesc']||' ')+'</div>'+
				'<div>线下培训</div><div>'+(index==0?'必修':'选修')+'</div><div>'+dict['DrillCredit']+'分</div></div>'+
				'<div class="classSubInfo">培训日期：'+dict['StartDate']+' - '+dict['EndDate']+'</div>';
			if (dict['OrderFlag'] != 'Y') {
				var isExpire = true
				for (var j = 0; j < TimeList.length; j++) {
					var oneTime = (TimeList[j].split('」')[2])||''
					if (oneTime == '') {
						continue
					}
					if (oneTime > currDateTime) {
						isExpire = false
					}
				}
				if (isExpire) {
					html +='<div class="baseBtn expire">报名</div>'
				}else{
					html +='<div id="'+(oldcount+i)+'-'+index+'-order" class="baseBtn">'+text+'</div>'
				}
			}else{
				var timeArr = TimeList[parseInt(dict['OrderNum'])-1].split('」')
				html +='<div class="classSubInfo">培训日期：'+(timeArr[0]||'')+' - '+(timeArr[1]||'')+'</div>'+
					'<div class="classSubInfo">培训地点：'+(timeArr[3]||'')+'</div>'+
					'<div id="'+(oldcount+i)+'-'+index+'-cancel" class="baseBtn cancel">取消'+text+'</div>'+
					'<div id="'+(oldcount+i)+'-'+index+'-canChange" class="baseBtn canChange">修改'+text+'</div>'
			}
			var newLi = document.createElement('li')
			mustUL.appendChild(newLi)
			newLi.setAttribute('class','mui-table-view-cell')
			newLi.innerHTML = html
		}
	}

	function getOptionData(){
		if (optionPulling) {
			optionPull.endPullUpToRefresh()
			return;
		}
		optionPulling = true
		var parr = '^^1^N^O'; //Y必修 N选修 1是主题
		var pdict = {'parr':parr,'input':$('#search')[0].value,'loginID':loginID,'start':optionStart,'limit':Limit}
		//console.log(JSON.stringify(pdict))
		var paramDict = {'method':'web.INMTeaComm:FindDrillReleaseList','params':JSON.stringify(pdict),'type':'RecQuery'}
		$.DHCWebService(paramDict, function(result) {
			//console.log(JSON.stringify(result))
			optionPulling = false
			if (result['msgcode'] != '1') {
				mui.toast(result.msg)
				optionPull.endPullUpToRefresh();
				return
			}
			var dataArr = result.data
			if (optionStart == 0) {
				mui('#optionUL').off('tap','.baseBtn',baseBtnTapped)
				optionData = dataArr
				$('#optionUL')[0].innerHTML = ''
				mui('#optionUL').on('tap','.baseBtn',baseBtnTapped)
			}else{
				optionData = optionData.concat(dataArr)
			}
			updateMustUI(dataArr,'optionUL')
			if (dataArr.length < Limit) {
				optionPull.endPullUpToRefresh(true);
			}else{
				optionPull.endPullUpToRefresh();
			}
			optionStart += dataArr.length;
		}, function(errorStr) {
			optionPull.endPullUpToRefresh();
			optionPulling = false
		});
	}
	function baseBtnTapped(){
		var classStr = this.getAttribute('class')
		if (classStr.indexOf('expire') >= 0) {
			mui.toast('已超过预约日期,无法预约')
			return
		}
		var index = parseInt(this.id)
		var type = parseInt(this.id.split('-')[1])
		var dict = mustData[index]
		if (type == 1) {
			dict = optionData[index]
		}
		if (classStr.indexOf('cancel') != -1) { //取消
			mui.confirm('确定要'+this.innerText+'该课程吗？',' ',['取消','确定'],function (e) {
				if (e.index == 1) {
					cancelOrderAction(dict,type);
				}
			},'div')
			return
		}
		toOrder(dict,type)
	}
	
	function cancelOrderAction(dict,type){
		var parr = dict['subID']+'^N^'; //subID^OrderFlag^OrderNum
		var pdict = {'parr':parr}
		//console.log(JSON.stringify(pdict))
		var paramDict = {'method':'web.INMTeaComm:SaveDrillOrder','params':JSON.stringify(pdict),'type':'Method'}
		$.DHCWebService(paramDict, function(result) {
			//console.log(JSON.stringify(result))
			if (result['msgcode'] != '1') {
				mui.toast(result['msg'])
			}else{
				refreshMainPage(type)
			}
		}, function(errorStr) {
			mui.toast(errorStr)
		});
	}
	function toOrder(dict,type){
		var webview = plus.webview.create('toOrder.html', 'toOrder', {
			background: '#fff',
			statusbar: {
				background: '#fff'
			}
		},{sourceData:dict,pageType:'class'});
		webview.show('fade-in');
		webview.addEventListener('close',function(){
			refreshMainPage(type)
		})
	}
	function baseSetup(){
		$('.mui-scroll-wrapper').scroll({
			bounce: true,
			indicators: false, //是否显示滚动条
		});
		mui('#mustUL').on('tap','.baseBtn',baseBtnTapped) 
		mui('#optionUL').on('tap','.baseBtn',baseBtnTapped) 
		var perInfo = app.getState()
		loginID = perInfo['loginID']
		TomcatUrl = perInfo.TomcatUrl
		mui("body").on("tap", ".searchArea .mui-icon-clear", function() {
			if (document.getElementById('search').value != "") {
				document.getElementById('search').value = ""
			}
			refreshMainPage()
		});
		var slider = document.getElementById('slider');
		slider.addEventListener('slide', function(event) {
			var index = event.detail.slideNumber;
			refreshMainPage(index)
			$('#sliderIndicator .mui-indicator[data-index="'+index+'"]')[0].classList.add('mui-active');
		});
		
		var indicators = document.querySelectorAll('#sliderIndicator .mui-indicator');
		for (var i = 0; i < indicators.length;i++) {
			indicators[i].addEventListener('tap',function(){
				var oldActive = $('#sliderIndicator .mui-indicator.mui-active')[0];
				if (oldActive) {
					if (oldActive == this) {
						return
					}
					oldActive.classList.remove('mui-active')
				}
				var newIndex = parseInt(this.getAttribute('data-index'))
				refreshMainPage(newIndex)
				this.classList.add('mui-active')
				mui('#slider').slider().gotoItem(newIndex,100)
			});
		}
		var search = document.getElementById('search');
		search.addEventListener('input',function(){
			refreshMainPage()
		});
		//待培训
		var mustScroll = document.getElementById('mustScroll');
		mustPull = $(mustScroll).pullToRefresh({
			up: {
				callback: function() {
					getMustData()
				}
			}
		});
		//待培训
		var optionScroll = document.getElementById('optionScroll');
		optionPull = $(optionScroll).pullToRefresh({
			up: {
				callback: function() {
					getOptionData()
				}
			}
		});
		
		getMustData();
		getOptionData();
	}
	function refreshMainPage(newIndex){
		if (newIndex == undefined) {
			resetMustRefresh();
			resetOptionRefresh()
			return
		}
		if (newIndex == 0){
			resetMustRefresh();
		}else if(newIndex == 1){
			resetOptionRefresh()
		}
	}
	function resetMustRefresh(){
		mustStart = 0;
		mustData = []
		mui('#mustUL').off('tap','.baseBtn',baseBtnTapped)
		$('#mustUL')[0].innerHTML = '';
		$('#mustWrapper').scroll().scrollTo(0,0,100);
		if (mustPull) {
			mustPull.refresh(true)
		}
		getMustData();
	}
	function resetOptionRefresh(){
		optionStart = 0;
		optionData = []
		mui('#optionUL').off('tap','.baseBtn',baseBtnTapped) 
		$('#optionUL')[0].innerHTML = '';
		$('#optionWrapper').scroll().scrollTo(0,0,100);
		if (optionPull) {
			optionPull.refresh(true)
		}
		getOptionData();
	}
	
	function getCurrDateTime(){
		var dateObj = new Date()
		var currMon = dateObj.getMonth() + 1
		var currDay = dateObj.getDate()
		var currDate = dateObj.getFullYear() +'-'+(currMon<10?('0'+currMon):currMon)+'-'+(currDay<10?('0'+currDay):currDay)
		var hourInt = dateObj.getHours()
		var minuteInt = dateObj.getMinutes()
		var currTime = (hourInt<10?('0'+hourInt):hourInt)+':'+(minuteInt<10?('0'+minuteInt):minuteInt)
		return currDate+' '+currTime
	}
})(mui);